import { defineStore } from 'pinia';
import { computed, reactive, ref } from 'vue';

export const useDownloadStore = defineStore('download', () => {
  const pageNum = ref(1);
  const downloadList = reactive([]);
  const pageSize = ref(12);
  const total = ref(0);
  const hasMore = computed(() => downloadList.length < total.value);
  
  // 添加下载列表
  const addDownloadList = (item) => {
    // 避免重复添加
    const exists = downloadList.some(download => download._id === item._id);
    if (!exists) {
      downloadList.push(item);
    }
  };
  
  // 批量添加下载列表
  const addDownloadListBatch = (items) => {
    items.forEach(item => addDownloadList(item));
  };
  
  // 重置分页
  const resetPagination = () => {
    pageNum.value = 1;
    downloadList.length = 0; // 清空数组
    total.value = 0;
  };
  
  // 设置总数
  const setTotal = (count) => {
    total.value = count;
  };
  
  // 下一页
  const nextPage = () => {
    pageNum.value++;
  };
  
  return {
    downloadList,
    pageNum,
    pageSize,
    total,
    hasMore,
    addDownloadList,
    addDownloadListBatch,
    resetPagination,
    setTotal,
    nextPage
  };
  
},
{ 
  persist: {
    key: 'download-store',
    paths: ['downloadList', 'pageNum', 'pageSize', 'total'],
  },
}
);
